<!--
 * @Description: 菜单配置-路由配置
-->
<template>
  <BaseMainSlot>
    <template v-slot:btnsBar>
      <ActionBar
        :has-add="false"
        :has-del="false"
        :has-edit="false"
        :has-cancel="true"
        :has-save="true"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        @cancel="cancel"
        @save="save"
      />
    </template>
    <template v-slot:typenodeslot>
      <Selectbut
        :topitem-select-list="topitemSelectList"
        @topitemtype="topitemtype"
      />
    </template>
    <template v-slot:tablebox>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="85%"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="
            nowselectypeindex === 0"
          type="index"
          label="序号"
          width="50"
        >
          <template
            slot-scope="scoped"
          >
            {{ scoped.row.roleId?scoped.$index+1:'' }}
          </template>

        </el-table-column>
        <el-table-column v-else type="index" label="序号" width="50">
          <template
            slot-scope="scoped"
          >
            {{ scoped.row.id?scoped.$index+1:'' }}
          </template>
        </el-table-column>

        <el-table-column v-if="nowselectypeindex === 0" prop="roleName" label="角色名称" />
        <el-table-column v-if="nowselectypeindex === 1" prop="username" label="姓名" />
        <el-table-column v-if="nowselectypeindex === 2" prop="username" label="姓名" />
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:form>
      <div v-if="nowselectypeindex === 0 || nowselectypeindex === 1">
        <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          node-key="routeId"
          :props="treePropstype"
          :default-checked-keys="defaultchecklist"
          @node-click="treeclick"
          @check="handleSionChange"
          @check-change="handleSelectionChange"
        />
      </div>
      <div v-if="nowselectypeindex === 2">
        <!-- <div>可选择菜单</div> -->
        <el-checkbox-group v-model="selectedidlist">
          <el-checkbox v-for="menuitem in menuList" :key="menuitem.routeId" :label="menuitem.routeId" :checked="menuitem.checked">
            {{ menuitem.menuName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Selectbut from "@/components/equipTypeSelectButton/selcetButton.vue";
import nowpagereq from "@/api/system-settings/menu-config/index";
import roleManage from "@/api/system-settings/role-manage";
import userManage from "@/api/system-settings/user-manage";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/tree.vue";
import { mymixin } from "@/utils/mixin";
import organizationrequest from "@/api/axios";
import { webServiceUrl } from "@/api/baseURL"
import { getToken } from "@/utils/auth";
export default {
  name: "MenuConfig",
  components: { BaseMainSlot, ActionBar, Selectbut, Pagination },
  mixins: [mymixin],
  data() {
    return {
      // ---手机端相关---
      // 选中的idlist
      selectedidlist: [],
      // 处理后的菜单数据
      menuList: [
      ],
      // 所有的菜单数据
      allmenuList: [],
      // 拥有的菜单数据
      hasmenuList: [],
      // ---end---
      nowselectypeindex: 0,
      roleList: [],
      userList: [],
      topitemSelectList: [
        { name: "角色路由配置", id: 0 },
        { name: "用户路由配置", id: 1 },
        { name: "手机端菜单配置", id: 2 }
      ],
      treePropstype: {
        children: "children",
        label: "metaName"
      },
      tableDataone: [],
      searchList: {},
      nowselectedList: [],
      treeData: [],
      //   farmtypelist: [],
      defaultchecklist: [],
      permisslist: [],
      userRouteMapperId: null,
      roleRouteMapperId: null,
      farmingTypeRouteMapperId: null,
      roleId: '',
      userId: '',
      farmingTypeId: '',
      saveActive: false,
      cancelActive: false
    };
  },
  watch: {},
  created() {
  },
  mounted() {
    this.getTableDataList();
  },
  methods: {
    // ---手机端相关---
    // ---- 菜单获取相关 ----
    // 获取所有的菜单数据
    getallmenulist() {
      nowpagereq.getallappmenulist().then(
        res => {
          let listone = res.data
          if (listone && listone.length > 0) {
            this.allmenuList = listone
          }
        }
      )
    },
    // 获取所拥有的菜单数据
    gethasmenulist(id = this.userId) {
      this.saveActive = true
      // this.cancelActive = true
      this.userId = id
      this.selectedidlist = []
      this.menuList = []
      this.hasmenuList = []
      this.userRouteMapperId = ""
      // let routerpid = getToken("routerpid")
      let orgid = getToken("organizationId")
      let params = {
        "userId": id,
        "organizationId": orgid
      }
      // if (routerpid === orgid) {
      //   console.log("选择同级的组织结构")
      // } else {
      //   params["parentId"] = orgid;
      //   params["organizationId"] = routerpid
      // }
      nowpagereq.gethasappmenulist(params).then(
        res => {
          let listone = res.data
          if (listone && listone.length > 0) {
            this.userRouteMapperId = "007"
            this.hasmenuList = listone
          } else {
            this.userRouteMapperId = ""
          }
          this.getlastmenulist()
        }
      )
    },
    // 处理菜单数据获取需要的值
    getlastmenulist() {
      let listone = this.allmenuList;
      let listtwo = this.hasmenuList;
      let listthree = [];
      let listfour = [];
      listthree = listtwo.map(
        itemtwo => {
          return itemtwo.routeId
        }
      )
      listfour = listone.map(
        itemone => {
          if (listthree.indexOf(itemone.routeId) === -1) {
            return {
              routeId: String(itemone.routeId),
              menuName: itemone.menuName,
              checked: false
            }
          } else {
            return {
              routeId: String(itemone.routeId),
              menuName: itemone.menuName,
              checked: true
            }
          }
        }
      )
      this.menuList = listfour
      // console.log(listfour)
    },
    // ---手机端end---
    // 获取当前选中的配置类型index
    topitemtype(e) {
      this.nowselectypeindex = e;
      let that = this
      that.$nextTick(() => {
        if (e !== 2) {
          that.$refs.tree.setCheckedNodes([]);
        } else {
          this.getallmenulist()
        }
      });
      this.currentPage = 1;
      this.getuserRoleTableDataList();
    },
    // 树状选中时节点数据
    treeclick(eone, etwo, ethree) {
      this.editActive = true;
      this.formData = eone;
    },
    // 所有种养类别树状图选中节点时触发
    handleSionChange() {
      this.saveActive = true
      this.cancelActive = true
    },
    // 所有种养类别树状图选中节点时触发
    handleSelectionChange() {
      // let arr = this.$refs.tree.getCheckedKeys().concat.apply([], this.$refs.tree.getHalfCheckedKeys())
      let list = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      // let list = Array.from(arr)
      // let list = arr
      // console.log(list)
      // console.log(list)
      this.permisslist = list
    //   this.nowselectedList = [];
    //   // const list = [...this.$refs.catetreetwo.getCheckedNodes(), ...this.$refs.catetreetwo.getHalfCheckedNodes()]
    //   const list = [...this.$refs.catetreetwo.getCheckedNodes()];
    //   this.nowselectedList = list.map((item) => {
    //     return item.plantingTypeId;
    //   });
    //   if (this.nowselectedList && this.nowselectedList.length > 0) { this.delActive = true; } else this.delActive = false;
    },
    // 获取下拉框数据
    // getselectdatalist() {
    //   nowpagereq.getroleAll().then((res) => {
    //     this.roleList = res.data;
    //     // this.getTableDataListrole()
    //   });
    //   nowpagereq.getuserAll().then((res) => {
    //     this.userList = res.data;
    //   });
    // },
    // 获取角色
    async getuserRoleTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
        //   roleName: this.roleName
        }
      };
      // 角色
      if (this.nowselectypeindex === 0) {
        const res = await roleManage.getPageList(params);
        this.loading = false;
        if (res.code === 1) {
          let data = res.data;
          // 赋值总条数
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
        } else {
          this.$message.error(res.msg)
        }
      } else if (this.nowselectypeindex === 1 || this.nowselectypeindex === 2) {
        // 用户
        params.entity.organizationNo = sessionStorage.organizationNo
        const res = await userManage.queryUserPageList(params);
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || {};
          // 赋值总条数
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
        } else {
          this.$message.error(res.msg)
        }
      }
      this.addblankmet();
    },
    // 表格查询 --- 获取所有路由
    getTableDataList() {
      this.treeData = [];
      // let accessedRoutes;
      // 是否启用动态路由
      // let nowmenutype = true
      // if (nowmenutype) {
      let menuurlone;
      let params = {};
      let routerpid = JSON.parse(getToken("routerpid"));
      let orgid = JSON.parse(getToken("organizationId"));
      if (routerpid === 0) {
        menuurlone = "powerManage/route/queryAllRouteTreeList";
      } else if (routerpid === orgid) {
        menuurlone = "powerManage/route/queryRouteTreeList";
      } else {
        menuurlone = "powerManage/route/queryRouteTreeListByUser";
        params['parentId'] = orgid
      }
      let menuurl = webServiceUrl + menuurlone;
      params['organizationId'] = routerpid
      organizationrequest.post(menuurl, params).then((res) => {
        if (res.code === 1) {
          let data = res.data;
          this.treeData = data;
          this.treeData.forEach((item) => {
            item.metaName = item.meta.name;
            this.$set(item, "metaName", item["meta"]["title"]);
            if (item.children) {
              item.children.forEach((itemTwo) => {
                // itemTwo.metaName = itemTwo.meta.name
                this.$set(itemTwo, "metaName", itemTwo["meta"]["title"]);
              });
            }
          });
          this.resetActionBar();
        } else {
          this.$message.error("查询失败");
        }
      });
      // 判断搜索输入框数据
    },
    // 获取角色拥有路由
    getTableDataListrole(id) {
      let roleId = id || 1;
      this.tableDataone = [];
      nowpagereq.getrolelist(roleId).then((res) => {
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        let PermissionList = res.data;
        // console.log(PermissionList)
        let that = this;
        that.$nextTick(() => {
          if (this.nowselectypeindex !== 2) {
            that.$refs.tree.setCheckedNodes([]);
          }
        });
        PermissionList.forEach((item) => {
          // nowcheck.push(item.functionPermissionId)
          that.$nextTick(() => {
            // console.log(item.functionPermissionId)
            // 设置目前所有节点
            // that.$refs.tree.setCheckedKeys([item.routeId], true)
            // 设置某个节点
            that.$refs.tree.setChecked(item.routeId, true);
          });
        });
        // this.checklist = nowcheck
        if (res.data) {
          this.roleRouteMapperId = "007";
        }
        // this.resetActionBar();
      });
      // 判断搜索输入框数据
    },
    // 获取用户拥有路由
    getTableDataListuser(id) {
      let userId = id || 1;
      this.tableDataone = [];
      nowpagereq.getuserlist(userId).then((res) => {
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        let PermissionList = res.data;
        // console.log(PermissionList)
        let that = this;
        that.$nextTick(() => {
          if (this.nowselectypeindex !== 2) {
            that.$refs.tree.setCheckedNodes([]);
          }
        });
        PermissionList.forEach((item) => {
          that.$nextTick(() => {
            // 设置某个节点
            that.$refs.tree.setChecked(item.routeId, true);
          });
        });
        if (res.data) {
          this.userRouteMapperId = "007";
        }
      });
      // 判断搜索输入框数据
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
      this.getuserRoleTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
      this.getuserRoleTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
      this.getuserRoleTableDataList();
    },
    // 取消
    cancel() {
      this.nowChanceStau = ''
      this.formData = {}
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false
    },
    handleEdit(row) {
      let that = this
      that.$nextTick(() => {
        if (this.nowselectypeindex !== 2) {
          that.$refs.tree.setCheckedNodes([]);
        }
      });
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = false;
      if (this.nowselectypeindex === 1) {
        this.getTableDataListuser(row.id);
        this.userId = row.id
        // console.log(row)
      } else if (this.nowselectypeindex === 0) {
        // this.getuserRoleTableDataList()
        this.getTableDataListrole(row.roleId);
        this.roleId = row.roleId
      } else if (this.nowselectypeindex === 2) {
        this.gethasmenulist(row.id);
        this.farmingTypeId = row.farmingTypeId
      }
    },
    // 删除时触发方法
    delmessage() {
      nowpagereq.dellist(this.nowSelectList).then((res) => {
        if (res.code === 1) {
          this.$message.success("删除成功！");
          this.getTableDataList();
        } else {
          this.$message.error("删除失败！");
        }
      });
    },
    async save() {
      if (this.nowselectypeindex === 0) {
        let par = {
          roleId: this.roleId,
          routeIdList: this.permisslist,
          organizationId: sessionStorage.organizationId,
          roleRouteMapperId: this.roleRouteMapperId || ''
        };
        nowpagereq.addrolelist(par).then((res) => {
          if (res.code === 1) {
            this.$message.success("修改成功！");
            this.cancel();
          } else {
            this.$message.success("修改失败！");
          }
        });
      } else if (this.nowselectypeindex === 1) {
        let par = {
          userId: this.userId,
          routeIdList: this.permisslist,
          organizationId: sessionStorage.organizationId,
          userRouteMapperId: this.userRouteMapperId || ''
        };
        nowpagereq.adduserlist(par).then((res) => {
          if (res.code === 1) {
            this.$message.success("修改成功！");
            this.cancel();
          } else {
            this.$message.success("修改失败！");
          }
        });
        console.log("设置权限");
      } else if (this.nowselectypeindex === 2) {
        let par = {
          userId: this.userId,
          routeIdList: this.selectedidlist,
          organizationId: sessionStorage.organizationId,
          userRouteMapperId: this.userRouteMapperId || ''
        };
        nowpagereq.saveappmenulist(par).then((res) => {
          if (res.code === 1) {
            this.$message.success("修改成功！");
            this.gethasmenulist;
            this.cancel();
          } else {
            this.$message.success("修改失败！");
          }
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-checkbox{
  color: #fff;
}
</style>
